package com.lagou.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("login")
public class LoginController {

    @Autowired
    private DataSource dataSource;

    @RequestMapping("toLogin")
    public String toLogin() {
        System.out.println("================++++++++++++++跳转登录页面");
        return "login";
    }

    @RequestMapping("loginSystem")
    public String loginSystem(String username, String password, HttpSession session) throws SQLException {

        Map<String, String> user = getUser(username, password);

        // 合法用户，信息写入session，同时跳转到系统主页面
        if(!user.isEmpty()) {
            System.out.println("合法用户");
            session.setAttribute("username",username + System.currentTimeMillis());
            session.setAttribute("password",password + System.currentTimeMillis());
            return "redirect:/demo/result";
        }else{
            // 非法用户返回登录页面
            System.out.println("非法，跳转");
            return "redirect:/login/toLogin";
        }
    }

    private Map<String, String> getUser(String username, String password) throws SQLException {
        Map<String,String> userMap = new HashMap<>();

        Connection connection = dataSource.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement("select * from user where username = ? and password = ?");
        preparedStatement.setString(1,username);
        preparedStatement.setString(2,password);
        ResultSet resultSet = preparedStatement.executeQuery();

        while (resultSet.next()){
            userMap.put(resultSet.getString("username"),resultSet.getString("password"));
        }
        connection.close();
        return userMap;
    }


}
